package com.suanfa.collect;

import jdk.nashorn.internal.parser.JSONParser;

import java.util.ArrayList;
import java.util.List;

/**
 * 求给定集合的所有子集
 */
public class SubCollect {

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3};
        List<ArrayList<Integer>>  result = getSub(arr);
        for(int  i =0; i< result.size(); i++){
            ArrayList<Integer> arrayList = result.get(i);
            for(int j = 0; j<arrayList.size(); j++){
                System.out.print(arrayList.get(j) + ",");
            }
            System.out.println();
        }
    }


    public static List<ArrayList<Integer>> getSub(int[] arr){

        List<ArrayList<Integer>> list = new ArrayList<>();
        int length = arr.length;
        int count = 2 << length - 1;
        for(int i=0; i<count; i++){
            String btr = Integer.toBinaryString(i);
            btr = resize(btr, length);
            list.add(parseSub(arr, btr));
        }
        return list;
    }

    public static ArrayList<Integer> parseSub(int[] arr, String str){
        ArrayList<Integer> result = new ArrayList<>();
        char[] chars = str.toCharArray();
        for(int i =0; i<chars.length; i++){
            if(chars[i] == '1'){
                result.add(arr[i]);
            }
        }
        return  result;
    }

    public static String resize(String str, Integer length){
        int diff = length - str.length();
        if(diff > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < diff; i++) {
                stringBuilder.append("0");
            }
            str = stringBuilder.append(str).toString();
        }
        return  str;
    }
}
